package com.jiguang.property.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jiguang.property.dto.OperateLogDTO;
import com.jiguang.property.dto.UserInfoDTO;
import com.jiguang.property.entity.OperateLog;
import com.jiguang.property.mapper.OperateLogMapper;
import com.jiguang.property.service.OperateLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiguang.property.utils.JwtUtils;
import com.jiguang.property.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2025-03-09
 */
@Service
public class OperateLogServiceImpl extends ServiceImpl<OperateLogMapper, OperateLog> implements OperateLogService {
    @Autowired
    private JwtUtils tokenManager;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public Result listBuildInfoByUserId(OperateLogDTO operateLogDTO) {
        //通过工具类获取Request对象
        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        //获取用户名
        //需要通过解析token获取
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            return Result.error().message("登陆过期");
        }
        String userId = tokenManager.getUserFromToken(token);

        QueryWrapper<OperateLog> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);

        //获取操作日志列表
        List<OperateLogDTO> operateLogDTOS = baseMapper.listBuildInfoByUserId(userId, operateLogDTO.getPageNow(),
                operateLogDTO.getPageSize());

        //获取列表总数
        Integer total = baseMapper.selectCount(wrapper);

        return Result.ok().data("operateLogList",operateLogDTOS).data("total",total);
    }


    @Override
    public Result getRecord() {
        //获取数据
        List<OperateLogDTO> recoredDTO = baseMapper.getRecored();
        return Result.ok().data("recoredDTO",recoredDTO);
    }
}
